package org.goyo.main.services.base.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import org.apache.commons.lang.StringUtils;
import org.goyo.common.baseBean.Constants;
import org.goyo.common.exception.DBException;
import org.goyo.common.exception.ServiceException;
import org.goyo.common.utils.DateUtils;
import org.goyo.common.utils.Pager;
import org.goyo.main.domain.dao.base.ICustomerDao;
import org.goyo.main.domain.dao.system.ISysUserDao;
import org.goyo.main.domain.entity.BaseObject;
import org.goyo.main.domain.entity.base.BaseUnitMeasure;
import org.goyo.main.domain.entity.base.Categories;
import org.goyo.main.domain.entity.base.Customer;
import org.goyo.main.domain.entity.base.Material;
import org.goyo.main.domain.entity.system.SysUser;
import org.goyo.main.domain.excelBean.CustomerExcel;
import org.goyo.main.domain.excelBean.MaterialExcel;
import org.goyo.main.services.BaseService;
import org.goyo.main.services.base.ICustomerService;
import org.goyo.main.services.system.IBillNumberService;
import org.goyo.main.services.system.impl.BillNumberServiceImpl;
import org.goyo.main.web.controller.system.SessionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
@Transactional
public class CustomerServiceImpl extends BaseService implements ICustomerService {
  protected Logger logger = LoggerFactory.getLogger(this.getClass());
	@Resource
	private ICustomerDao customerDao;
	@Resource
	private IBillNumberService billNumberService;
	@Resource
	private ISysUserDao sysUserDao;

	@Override
	public Pager<Customer> findByCondition(String where, Pager pager)
			throws DBException, ServiceException {
		
		return  customerDao.findByCond(where, pager);
	}

	@Override
	public BaseObject saveOrUpdateInfo(Customer info) throws DBException,
			ServiceException {
		String uuid = null;
		String date = DateUtils.parseDate("yyyy-MM-dd", new Date());
		SysUser user = (SysUser)SessionUtil.getAttribute("user");
		//保存用户数据
		if(info.getUuid() == null || "".equals(info.getUuid())){
			info.setUuid(null);
			info.setStatus(Constants.SAVESTATUS);
			info.setCreateDate(date);
			info.setCreateUser(user);
			info.setAlterDate(date);
			info.setAlterUser(user);
//			alterBillNumber(Customer.BIZTYPE, info.getNumber());
			uuid = customerDao.save(info);
		}else{
			info.setAlterDate(date);
			info.setAlterUser(user);
			customerDao.update(info);
			uuid = info.getUuid();
		}
		
		BaseObject obj = new  BaseObject();
		obj.setCreateDate(date);
		obj.setCreateUser(user);
		obj.setAlterDate(date);
		obj.setAlterUser(user);
		obj.setUuid(uuid);
		obj.setStatus(Constants.SAVESTATUS);
		return obj;
	}

	@Override
	public void delByUuids(Object[] uuids) throws DBException, ServiceException {
		for(Object uuid : uuids){
			Customer customer  = customerDao.get(Customer.class, uuid.toString());
			customerDao.delete(customer);
		}
//		customerDao.delBatch(Customer.class, "uuid", uuids);
	}

	@Override
	public Customer findByUuid(String uuid) throws DBException,
			ServiceException {
		return customerDao.get(Customer.class, uuid);
	}

	@Override
	public BaseObject submitInfo(Object[] uuids) throws DBException, ServiceException {
		String date = DateUtils.parseDate("yyyy-MM-dd", new Date());
		SysUser user = (SysUser)SessionUtil.getAttribute("user");
		for(Object uuid : uuids){
			Customer customer  = customerDao.get(Customer.class, uuid.toString());
			customer.setAlterDate(date);
			customer.setAlterUser(user);
			customerDao.update(customer);
		}
		BaseObject obj = new BaseObject();
		obj.setAlterDate(date);
		obj.setAlterUser(user);
		obj.setStatus(Constants.SUBMITTATUS);
		return obj;
	}

	@Override
	public BaseObject auditInfo(Object[] uuids) throws DBException, ServiceException {
		String date = DateUtils.parseDate("yyyy-MM-dd", new Date());
		SysUser user = (SysUser)SessionUtil.getAttribute("user");
		for(Object uuid : uuids){
			Customer customer  = customerDao.get(Customer.class, uuid.toString());
			customer.setAlterDate(date);
			customer.setAlterUser(user);
			customer.setAuditDate(date);
			customer.setAuditUser(user);
			customerDao.update(customer);
		}
		BaseObject obj = new BaseObject();
		obj.setAlterDate(date);
		obj.setAlterUser(user);
		obj.setAuditDate(date);
		obj.setAuditUser(user);
		obj.setStatus(Constants.AUDITSTATUS);
		return obj;
	}

	@Override
	public BaseObject unAuditInfo(Object[] uuids) throws DBException,
			ServiceException {
		String date = DateUtils.parseDate("yyyy-MM-dd", new Date());
		SysUser user = (SysUser)SessionUtil.getAttribute("user");
		for(Object uuid : uuids){
			Customer customer  = customerDao.get(Customer.class, uuid.toString());
			customer.setAlterDate(date);
			customer.setAlterUser(user);
			customer.setAuditDate(null);
			customer.setAuditUser(null);
			customerDao.update(customer);
		}
		BaseObject obj = new BaseObject();
		obj.setAlterDate(date);
		obj.setAlterUser(user);
		obj.setAuditDate(null);
		obj.setAuditUser(null);
		obj.setStatus(Constants.SAVESTATUS);
		return obj;
	}

  @Override
  public boolean checkNumberUsed(String uuid,String number) throws DBException, ServiceException {
    int i =0;
    try {
      String hql = "";
      if(StringUtils.isEmpty(uuid)){
        hql = "select count(*) from Customer where number='"+number+"'";
      }else{
        hql = "select count(*) from Customer where uuid !='"+uuid+"' and number='"+number+"'";
      }
      List list =  customerDao.findObjects(hql, null, null);
      if(null!=list && list.size()>0 && (Long)list.get(0)>0){
       return true;
      }else{
        return false;
      }
    } catch (Exception e) {
      logger.error(e.getMessage(),e);
      return false;
    }
  }
  
  
  
  @Override
  public void saveOrUpdateCustomerList(List<CustomerExcel> list) throws DBException, ServiceException {
    SysUser user = (SysUser)SessionUtil.getAttribute("user");
    for (CustomerExcel customerExcel : list) {
      try {
        Customer m = null;

        if(null==m){
          m = new Customer();
        }
        m.setName(customerExcel.getName());
        m.setNumber(billNumberService.getBaseNumber(Customer.BIZTYPE));
        m.setName(customerExcel.getName());
        m.setVipNumber(customerExcel.getVipNumber());
        m.setPersonalMobilePhone(customerExcel.getPersonalMobilePhone());
        m.setCity(customerExcel.getCity());
        m.setAddress(customerExcel.getAddress());

        if(!StringUtils.isEmpty(customerExcel.getSubCustomerManager())){
        	m.setSubCustomerManager((SysUser)sysUserDao.findUnique("from SysUser where trueName=?",  new Object[]{customerExcel.getSubCustomerManager()}));
//          m.setMatCategory((Categories) customerDao.findUnique("from Categories where number=? ", new Object[]{materialExcel.getMatCategoryCode()}));
        }
//        if(!StringUtils.isEmpty(materialExcel.getBaseUnit())){
//          m.setBaseUnit((BaseUnitMeasure) customerDao.findUnique("from BaseUnitMeasure where name=?", new Object[]{materialExcel.getBaseUnit()}));
//        }
//        if(!StringUtils.isEmpty(materialExcel.getExpiraDataUtil())){
//          switch (materialExcel.getExpiraDataUtil()) {
//            case "年":
//              m.setExpiraDataUtil("year");
//              break;
//            case "季度":
//              m.setExpiraDataUtil("quarter");
//              break;
//            case "月":
//              m.setExpiraDataUtil("month");
//              break;
//            case "星期":
//              m.setExpiraDataUtil("week");
//              break;
//            case "天":
//              m.setExpiraDataUtil("day");
//              break;
//            case "小时":
//              m.setExpiraDataUtil("hour");
//              break;
//            default:
//              break;
//          }
//        }
//        if(!StringUtils.isEmpty(materialExcel.getCreateUserName())){
//          SysUser su = sysUserDao.findByUserName(materialExcel.getCreateUserName());
//          m.setCreateUser(null==su?user:su);
//        }
//        if(!StringUtils.isEmpty(materialExcel.getUpdateUserName())){
//          SysUser su = sysUserDao.findByUserName(materialExcel.getUpdateUserName());
//          m.setAlterUser(null==su?user:su);
//        }
        
        customerDao.saveOrUpdate(m);
      } catch (Exception e) {
       logger.error(e.getMessage(),e);
       throw e;
      }
     
    }
    
  }
}
